//
//  YWSelectPatrolLineTableViewController.m
//  maintain
//
//  Created by Kyo on 16/9/8.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWSelectPatrolLineTableViewController.h"
#import "UIColor+CustomColors.h"
#import "YWMacro.h"
#import "YWCommonTool.h"
#import "MJRefresh.h"

#import "YWBuilding.h"
#import "YWSelectInspectionLineCell.h"

#import "YWKeepWatchMission.h"
#import "YWKeepWatchMissionManager.h"
#import "YWShowPatrolLineTableViewController.h"
#import "YWCreatePatrolLineTableViewController.h"

@interface YWSelectPatrolLineTableViewController ()<YWSelectInspectionLineCellDelegate>{
    YWPatrolLineOption *selectedPatrolLineOption;
    NSIndexPath *lastIndexPath;
}
@property (nonatomic, strong) NSArray *allPatrolLineOptions;
@property (nonatomic, strong) UILabel *headLabel;
@end

@implementation YWSelectPatrolLineTableViewController
- (instancetype)init{
    return [super initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"selectPatrolLine", nil);
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"finish", nil) style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemEvent:)];
    
    [self setupNotifications];
    [self initTableView];
}

- (void)setupNotifications{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTop) name:KRefreshCreatePatrolLineNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTop) name:KRefreshDeletePatrolLineNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTop) name:KRefreshModifyPatrolLineNotification object:nil];
}

- (void)initTableView{
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.separatorColor = [UIColor customLineColor];
    self.tableView.rowHeight = 44.0f;
    self.tableView.tableHeaderView = self.headLabel;
    //self.tableView.tableFooterView = [[UIView alloc]init];
    
    [self.tableView setEditing:YES];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshTop)];
    // 马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
}

- (void)refreshTop{
    YWWeakSelf(weakSelf);
    [[YWKeepWatchMissionManager shareManager] requestPatrolLineWithBuildingId:self.building.buildingId Complete:^(NSArray *lineArray) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.tableView.mj_header endRefreshing];
            if (lineArray.count > 0) {
                weakSelf.allPatrolLineOptions = lineArray;
                [weakSelf setupLineOption];
                [weakSelf.tableView reloadData];
            }
        });
    }];
}

//-(NSArray *)allInspectionLines{
//    if (!_allInspectionLines) {
//        _allInspectionLines = [[YWInspectionMissionManager shareManager] allInspectionLines];
//    }
//    return _allInspectionLines;
//}

- (void)setupLineOption{
    if (_ownPatrolLineOption) {
        NSInteger patrolLineId = _ownPatrolLineOption.patrolLineId;
        NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:@"%K = %ld", @"patrolLineId", patrolLineId];
        
        //NSMutableArray *searchResults = [_ownContacts mutableCopy];
        NSArray *array = [[self.allPatrolLineOptions filteredArrayUsingPredicate:searchPredicate] mutableCopy];
        if (array.count>0) {
            selectedPatrolLineOption = array[0];
        }
    }
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.allPatrolLineOptions.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YWSelectInspectionLineCell *cell = [YWSelectInspectionLineCell cellWithTableView:tableView];
    YWPatrolLineOption *lineOption = self.allPatrolLineOptions[indexPath.row];
    cell.lineOption = lineOption;
    cell.delegate = self;
    return cell;
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    YWPatrolLineOption *lineOption = self.allPatrolLineOptions[indexPath.row];
    if (lineOption.patrolLineId == selectedPatrolLineOption.patrolLineId) {
        [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
    }else{
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
    }
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    YWPatrolLineOption *lineOption = self.allPatrolLineOptions[indexPath.row];    if (lineOption.patrolLineId != selectedPatrolLineOption.patrolLineId) {
        selectedPatrolLineOption = lineOption;
    }
    if (lastIndexPath) {
        [tableView deselectRowAtIndexPath:lastIndexPath animated:NO];
    }else{
        [self.tableView reloadData];
    }
    lastIndexPath = indexPath;
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    YWPatrolLineOption *lineOption = self.allPatrolLineOptions[indexPath.row];
    if (lineOption.patrolLineId == selectedPatrolLineOption.patrolLineId) {
        selectedPatrolLineOption = nil;
    }
    lastIndexPath = nil;
}

- (void)rightBarButtonItemEvent:(id)sender{
    if (selectedPatrolLineOption) {
        if ([self.delegate respondsToSelector:@selector(popSelectedPatrolLine:)]) {
            [self.delegate popSelectedPatrolLine:selectedPatrolLineOption];
            [self.navigationController popViewControllerAnimated:YES];
        }
    }else{
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"selectOneLine", nil)];
    }
}

#pragma mark - YWSelectInspectionLineCellDelegate
- (void)clickInspectionLineButton:(UITableViewCell *)cell{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    YWPatrolLineOption *lineOption = self.allPatrolLineOptions[indexPath.row];
    YWShowPatrolLineTableViewController *showLineVC = [[YWShowPatrolLineTableViewController alloc] init];
    showLineVC.patrolLineOption = lineOption;
    [self.navigationController pushViewController:showLineVC animated:YES];
}

- (UILabel *)headLabel{
    if (!_headLabel) {
        UILabel *headLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
        _headLabel = headLabel;
        headLabel.backgroundColor = [UIColor whiteColor];
        headLabel.font=  kContentFont;
        headLabel.text = NSLocalizedString(@"makeNewKeepWatchLine", nil);
        headLabel.userInteractionEnabled = YES;
        [headLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickHeadLabelEvent:)]];
    }
    return _headLabel;
}

- (void)clickHeadLabelEvent:(id)sender{
    YWCreatePatrolLineTableViewController *createPatrolLineVC = [[YWCreatePatrolLineTableViewController alloc] init];
    createPatrolLineVC.buildingId = self.building.buildingId;
    [self.navigationController pushViewController:createPatrolLineVC animated:YES];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
